package com.tl.sboot.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.tl.sboot.entity.Proxy;
import com.tl.sboot.entity.Route;
import com.tl.sboot.entity.Services;
import com.tl.sboot.entity.User;
import com.tl.sboot.service.UserService;
import com.tl.sboot.utils.HttpRequest;
import com.tl.sboot.utils.JsonUtil;
import com.tl.sboot.utils.URLConnectionUtil;

import net.sf.json.JSONObject;
@Service
@SuppressWarnings("unchecked")
public class UserServiceImpl implements UserService{

	@Override
	public List<User> getUserList() {
        String json = HttpRequest.sendGet("http://quant.tuling.me/hub/api/users",null,getHeaders());
		List<User> userList = (List<User>) JsonUtil.parseJsonArrayToBean(json, User.class);
		return userList;
	}

	@Override
	public List<Services> getServicesList() {
		String json = HttpRequest.sendGet("http://quant.tuling.me/hub/api/services",null,getHeaders());
		List<Services> servicesList = (List<Services>) JsonUtil.parseJsonArrayToBean(json, Services.class);
		return servicesList;
	}

	@Override
	public void addUser(String userName, boolean admin) {
		Map<String, Object> params = new HashMap<String, Object>();
		List<String> usernames = new ArrayList<String>();
		usernames.add(userName);
		params.put("usernames",usernames);
		params.put("admin",false);
		Gson gson = new Gson();
		String jsonParams = gson.toJson(params);
		System.out.println("传入参数："+jsonParams);
		String sendPost = HttpRequest.sendPost("http://quant.tuling.me/hub/api/users",jsonParams, getHeaders());
		System.out.println("添加user返回的参数:"+sendPost);
	}
	
	
	public Map<String, String> getHeaders(){
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Authorization", "token a194a7d7e7f546c6a2d6e2fa227296aa");
		return headers;
	}

	@Override
	public void delUser(String userName) {
		boolean doDelete = URLConnectionUtil.doDelete("http://quant.tuling.me/hub/api/users/"+userName,null, getHeaders());
		if (doDelete) {
			System.out.println("删除数据成功");
		}else {
			System.out.println("删除数据错误");
		}
	}

	@Override
	public List<Proxy> getProxys() {
		String result = URLConnectionUtil.doGet("http://quant.tuling.me/hub/api/proxy", null, getHeaders());
     	JSONObject jsonObject = JSONObject.fromObject(result);
		Set<String> keySet = jsonObject.keySet();
     	List<Proxy> proxies = new ArrayList<Proxy>();
     	for (String object : keySet) {
			JSONObject jsonRoute = (JSONObject) jsonObject.get(object);
			Route bean = (Route) JSONObject.toBean(jsonRoute,Route.class);
			Map<String, Route> map = new HashMap<String, Route>();
			map.put(object, bean);
			Proxy proxy = new Proxy();
			proxy.setMap(map);
			proxies.add(proxy);
		}
		return proxies;
	}

}
